package com.omazan.db;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;

import com.omazan.db.models.User;
import com.omazan.utils.OmazanException;

public class HandleUsers {

	public User readUserFromDBUsingId(int id) throws OmazanException {

		User user = null;
		try {
			SessionFactory sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();

			// get new session
			Session session = sessionFactory.openSession();
			session.beginTransaction();

			user = (User) session.get(User.class, id);
			return user;
		} catch (HibernateException e) {

			e.printStackTrace();
			return null;

		}

	}

	@SuppressWarnings("unchecked")
	public List<User> readAllUsersFromDB() throws OmazanException {

		List<User> listOfUsers = new ArrayList<User>();
		Session session = null;

		try {

			session = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation().openSession();

			Query query = session.createQuery("from User").setResultTransformer(
					CriteriaSpecification.DISTINCT_ROOT_ENTITY);

			listOfUsers = (List<User>) query.list();

		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}

		return listOfUsers;
	}

	public boolean insertUser(User obj) throws OmazanException {


		try {

			SessionFactory sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();

			// get new session
			Session session = sessionFactory.openSession();
			session.beginTransaction();

			session.save(obj);
			session.getTransaction().commit();
			session.close();
			return true;

		} catch (HibernateException e) {

			e.printStackTrace();
			return false;

		}

	}
	
	public boolean deleteUsingId(int id){
		
		
		SessionFactory sessionFactory;
		try {
			sessionFactory = GeneralDBMethods.getInstance()
					.getSessionFactoryForDbOperation();
			Session session = sessionFactory.openSession();  
			session.beginTransaction();  
			User user = readUserFromDBUsingId(id);
			session.delete(user);  
			session.getTransaction().commit(); 
			
		} catch (OmazanException e) {
			
			e.printStackTrace();
			return false;
		}		
		
		return true;
	}

}
